package study.async.springboot.support.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Configuration
public class _3_AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //thread name prefix
        executor.setThreadNamePrefix("spring-pool-thread-");
        //thread size
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(5);
        //queue size
        executor.setQueueCapacity(0);
        //keep alive
        executor.setKeepAliveSeconds(5);
        //reject handler
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        AsyncUncaughtExceptionHandler handler = (ex, method, params) -> {
            log.error("异步执行任务异常: message {}, method {}, params {}", ex, method, params);
        };
        return handler;
    }
}
